package com.waypolice.manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.DocumentException;
import com.waypolice.base.BaseController;
import com.waypolice.common.constant.CmsResult;
import com.waypolice.common.constant.CmsResultConstant;
import com.waypolice.common.pdfUtil.ProducePdf;
import com.waypolice.common.utils.DateTimeUtil;
import com.waypolice.common.utils.FastDfsClient;
import com.waypolice.common.utils.PageUtils;
import com.waypolice.common.utils.StringUtil;
import com.waypolice.manager.service.UpmsArchivesTypesService;
import com.waypolice.manager.service.UpmsDictionaryService;
import com.waypolice.manager.service.UpmsOrganizationService;
import com.waypolice.manager.service.VolAndItemService;
import com.waypolice.mapper.CmsJudItemMapper;
import com.waypolice.mapper.CmsJudVolumeMapper;
import com.waypolice.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.omg.PortableInterceptor.ServerRequestInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @Description 归档管理
 * @Author wangrang
 * @Date Created in 14:08 2019/3/14
 * @Modified By:
 */
@Controller
@Api(value = "归档管理", description = "归档管理操作")
@RequestMapping(value="/pcwindow")
public class VolAndItemSortOutAction extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(VolAndItemSortOutAction.class);

    @Autowired
    private VolAndItemService volAndItemService;

    @Autowired
    private CmsJudItemMapper cmsJudItemMapper;

    @Autowired
    private CmsJudVolumeMapper cmsJudVolumeMapper;

    @Autowired
    private UpmsArchivesTypesService upmsArchivesTypesService;

    @Autowired
    private UpmsDictionaryService upmsDictionaryService;

    @Autowired
    private UpmsOrganizationService upmsOrganizationService;

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    /**
     * @author:wr
     * @description 跳转到归档管理页面
     * @date:
     * @return
     */
    @ApiOperation(value = "跳转到归档管理页面")
    @RequestMapping("/enter/sortOutArchive")
    public String toVolItemManagement(){
        return "preArchive/sortOutArchive";
    }

    @ApiOperation(value = "归档管理卷数据查询")
    @RequestMapping(value = "/volumeArchive/volList", method = RequestMethod.GET)
    @ResponseBody
    public Object volList(HttpServletRequest request,
                          @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                          @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                          @RequestParam(required = false, value = "sort") String sort,
                          @RequestParam(required = false, value = "order") String order,
                          String volTitle, String volNo,String volArchiveStatus) {

        boolean boo = StringUtils.isNotBlank(volTitle) || StringUtils.isNotBlank(volNo) || StringUtils.isNotBlank(volArchiveStatus);
        List<CmsJudVolume> cmsJudVolumes=null;
        if(boo){
            CmsJudVolumeExample cmsJudVolumeExample = new CmsJudVolumeExample();
            CmsJudVolumeExample.Criteria criteria = cmsJudVolumeExample.createCriteria();
            if(StringUtils.isNotBlank(volTitle)){
                criteria.andVolTitleLike("%"+volTitle+"%");}
            if(StringUtils.isNotBlank(volNo)){
                criteria.andVolNoEqualTo(volNo);}
            if(StringUtils.isNotBlank(volArchiveStatus)){
                String[] volArchiveStatuss = volArchiveStatus.split(",");
                List<Integer> volArchiveStatusList = new ArrayList<>();
                for(String str : volArchiveStatuss){
                    volArchiveStatusList.add(Integer.valueOf(str));
                }
                criteria.andVolArchiveStatusIn(volArchiveStatusList);
            }else {
                //待归档
                criteria.andVolArchiveStatusEqualTo(1);
            }
            if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
                sort= StringUtil.frontStrongToOracleString(sort);
                cmsJudVolumeExample.setOrderByClause(sort + " " + order);
            }else {
                cmsJudVolumeExample.setOrderByClause("\"VOL_CREATE_DATE\" DESC");
            }
            cmsJudVolumes = volAndItemService.selectAllByQueryParms(cmsJudVolumeExample);
        }else {
            CmsJudVolumeExample cmsJudVolumeExample = new CmsJudVolumeExample();
            CmsJudVolumeExample.Criteria criteria = cmsJudVolumeExample.createCriteria();
            //待归档
            criteria.andVolArchiveStatusEqualTo(1);
            if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
                sort= StringUtil.frontStrongToOracleString(sort);
                cmsJudVolumeExample.setOrderByClause(sort + " " + order);
            }else {
                cmsJudVolumeExample.setOrderByClause("\"VOL_CREATE_DATE\" DESC");
            }
            cmsJudVolumes = volAndItemService.selectAllByQueryParms(cmsJudVolumeExample);
        }

        //最终的list集合,分页操作
        PageUtils<CmsJudVolume> pageUtils = new PageUtils<CmsJudVolume>();
        List<CmsJudVolume> cmsJudVolumesPage = pageUtils.pageList(cmsJudVolumes, offset, limit);

        Map<String, Object> result = new HashMap<>();
        result.put("rows",cmsJudVolumesPage);
        result.put("total",cmsJudVolumes.size());
        return result;
    }

    @ApiOperation(value = "归档管理卷内件数据查询")
    @RequestMapping(value = "/itemArchive/itemList", method = RequestMethod.GET)
    @ResponseBody
    public String itemList(HttpServletRequest request,
                           @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                           @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                           String strParentID) {

        List<CmsJudItem> cmsJudItems = volAndItemService.selectAllByVolId(Long.valueOf(strParentID),2);
        JSONArray jsonArray = JSONArray.fromObject(cmsJudItems);
        String string = jsonArray.toString();
        return string;
    }

    @ApiOperation(value = "预归档驳回")
    @RequestMapping(value = "/sortOut/turnDown", method = RequestMethod.POST)
    @ResponseBody
    public String turnDown(HttpServletRequest request,String ids) {
        if(StringUtils.isNotBlank(ids)){
            String[] idArray = ids.split("-");
            ArrayList<String> objDown = new ArrayList<>();
            for (String id : idArray) {
                CmsJudVolume cmsJudVolume2 = volAndItemService.selectCmsJudVolumeByVolId(Long.valueOf(id));
                CmsJudVolume cmsJudVolume = new CmsJudVolume();
                cmsJudVolume.setVolId(Long.valueOf(id));
                cmsJudVolume.setVolArchiveStatus(3);
                int i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume);
                if(i!=1){
                    CmsJudVolume cmsJudVolume1 = volAndItemService.selectCmsJudVolumeByVolId(Long.valueOf(id));
                    objDown.add(cmsJudVolume1.getVolNo());
                }
            }
            if(objDown.size() ==0){
                return "success";
            }else {
                String join = StringUtils.join(objDown.toArray(), ",");
                // return join+"卷宗提交失败,请注意查看是否全部挂接原文!";
                return join+"案卷号驳回失败,请稍后重试1";
            }
        }
        return "请选中一行数据!";
    }

    @RequestMapping("/sort/carrierType")
    public String carrierType() {
        return "preArchive/carrierTypeSort";
    }

    @ApiOperation(value = "归档")
    @RequestMapping(value = "/sortOut/submitArchive", method = RequestMethod.POST)
    @ResponseBody
    public String submitArchive(HttpServletRequest request,String ids) {
    //public String submitArchive(HttpServletRequest request,String ids,String volCarrierValue) {
        if(StringUtils.isNotBlank(ids)){
            String[] idArray = ids.split("-");
            int volFlag=0;
            int itemCount=0;
            for (String id : idArray) {
                //案卷生成档号
                CmsJudVolume cmsJudVolume2 = volAndItemService.selectCmsJudVolumeByVolId(Long.valueOf(id));
                //归档日期
                cmsJudVolume2.setVolArchiveDate(DateTimeUtil.getNow());
                //修改日期
                cmsJudVolume2.setVolEditDate(DateTimeUtil.getNow());
                List<CmsJudItem> cmsJudIt = volAndItemService.selectAllByVolId(cmsJudVolume2.getVolId(), 2);
                ArrayList<Long> objects = new ArrayList<>();
                //添加载体类型
                if(StringUtils.isBlank(cmsJudVolume2.getVolCarrier())){
                    // cmsJudVolume.setVolCarrier(volCarrierValue);
                    cmsJudVolume2.setVolArchiveStatus(5);
                    cmsJudVolume2.setVolStr5("6");
                    int i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume2);
                    volFlag+=1;
                    continue;
                }
                String errorInfo=null;
                for (CmsJudItem cmsJudItem : cmsJudIt) {
                    //获取页次,为页数校验提供依据
                    objects.add(Long.valueOf(cmsJudItem.getItemPage()));
                    //校验原文
                    if(!"0".equals(cmsJudVolume2.getVolCarrier())){
                        if(StringUtils.isBlank(cmsJudItem.getItemStr2())){
                            errorInfo= "案卷中存在件未挂接原文,请挂接原文!";
                            break;
                        }
                    }

                }
                if(objects.size()==0){
                    //卷归档错误
                    cmsJudVolume2.setVolArchiveStatus(5);
                    cmsJudVolume2.setVolStr5("3");
                    int i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume2);
                    volFlag+=1;
                    continue;
                }
                //先排序后逆序,reverse方法只逆序,但不排序
                Collections.sort(objects);
                Collections.reverse(objects);
                Long aLong = objects.get(0);
                Long totalPage =0L;
                if(StringUtils.isNotBlank(cmsJudVolume2.getVolTotalPage()) && DateTimeUtil.isNumber(cmsJudVolume2.getVolTotalPage())){
                    String volTotalPage = cmsJudVolume2.getVolTotalPage();
                    totalPage=Long.valueOf(volTotalPage);
                }
                if(StringUtils.isNotBlank(errorInfo)){
                    //卷归档错误
                    cmsJudVolume2.setVolArchiveStatus(5);
                    cmsJudVolume2.setVolStr5("4");
                    int i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume2);
                    volFlag+=1;
                    continue;
                }else if(aLong>totalPage || objects.size()==0L){
                    //校验页次
                    //卷归档错误
                    cmsJudVolume2.setVolArchiveStatus(5);
                    cmsJudVolume2.setVolStr5("5");
                    int i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume2);
                    volFlag+=1;
                    continue;
                }

                //添加件数
                cmsJudVolume2.setVolItemNumber(String.valueOf(cmsJudIt.size()));

                //生成档号
                String fileNumber = null;
                try {
                    fileNumber = volAndItemService.getFileNumber(cmsJudVolume2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if("error".equals(fileNumber) || StringUtils.isBlank(fileNumber)){
                    cmsJudVolume2.setVolArchiveStatus(5);
                    cmsJudVolume2.setVolStr5("7");
                    int i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume2);
                    volFlag+=1;
                    continue;
                }
                //*******************
                String volCaseNum = cmsJudVolume2.getVolCaseNum();

                if(StringUtils.isNotBlank(volCaseNum) && !volCaseNum.trim().equals(fileNumber.trim())){
                    cmsJudVolume2.setVolStr4(fileNumber);
                    //卷归档错误
                    cmsJudVolume2.setVolArchiveStatus(5);
                    cmsJudVolume2.setVolStr5("1");
                    int i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume2);
                    volFlag+=1;
                }else {
                    int itemFlag=0;
                    //添加件号
                    List<CmsJudItem> cmsJudItems = volAndItemService.selectAllByVolId(Long.valueOf(id),2);
                    for (CmsJudItem cmsJudItem : cmsJudItems) {
                        //String str = String.format("%04d", cmsJudItem.getItemPage());
                        //将 件号=档号+页次 修改为 件号=档号+序号
                        String str = String.format("%04d", cmsJudItem.getItemNum());
                        String fileItemNumber = fileNumber + "-" + str;
                        if(StringUtils.isNotBlank(cmsJudItem.getItemStr1()) && !fileItemNumber.trim().equals(cmsJudItem.getItemStr1().trim())){
                            cmsJudItem.setItemStr7(fileItemNumber);
                            itemFlag+=1;
                        }else {
                            cmsJudItem.setItemStr1(fileItemNumber);
                        }
                        cmsJudItem.setItemStr11Date(DateTimeUtil.getNow());
                        int i1 = cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
                    }
                    cmsJudVolume2.setVolCaseNum(fileNumber);
                    if(itemFlag==0){
                        cmsJudVolume2.setVolArchiveStatus(2);
                    }else {
                        //卷内件归档错误
                        cmsJudVolume2.setVolArchiveStatus(5);
                        cmsJudVolume2.setVolStr5("2");
                        volFlag+=1;
                    }
                    int i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume2);
                    itemCount+=itemFlag;
                }

            }
            if(volFlag ==0 && itemCount == 0){
                return "success";
            }else {
                String info="归档失败"+volFlag+"卷，"+itemCount+"件,请查看归档失败列表。";
                return info;
            }
        }
        return "请选中一行数据!";

    }

    @ApiOperation(value = "使用新档号归档")
    @RequestMapping(value = "/volErrorArchive", method = RequestMethod.POST)
    @ResponseBody
    public String nowVolError(HttpServletRequest request,String volId,String archiveStatus) {
        //案卷生成档号
        CmsJudVolume cmsJudVolume2 = volAndItemService.selectCmsJudVolumeByVolId(Long.valueOf(volId));
        //归档日期
        cmsJudVolume2.setVolArchiveDate(DateTimeUtil.getNow());
        //修改日期
        cmsJudVolume2.setVolEditDate(DateTimeUtil.getNow());
        List<CmsJudItem> cmsJudIt = volAndItemService.selectAllByVolId(cmsJudVolume2.getVolId(), 2);
        ArrayList<Long> objects = new ArrayList<>();

        //添加载体类型
        if (StringUtils.isBlank(cmsJudVolume2.getVolCarrier())) {
            return "载体类型为空";
        }
        String errorInfo = null;
        for (CmsJudItem cmsJudItem : cmsJudIt) {
            //获取页次,为页数校验提供依据
            objects.add(Long.valueOf(cmsJudItem.getItemPage()));
            //校验原文
            if(!"0".equals(cmsJudVolume2.getVolCarrier())){
                if (StringUtils.isBlank(cmsJudItem.getItemStr2())) {
                    errorInfo = "案卷中存在件未挂接原文,请挂接原文!";
                    break;
                }
            }

        }
        if (objects.size() == 0) {
            //卷归档错误
            return "无卷内件";
        }
        //先排序后逆序,reverse方法只逆序,但不排序
        Collections.sort(objects);
        Collections.reverse(objects);
        Long aLong = objects.get(0);
        if (StringUtils.isNotBlank(errorInfo)) {
            //卷归档错误
            return "卷内件未挂接原文";
        } else if (aLong > Long.valueOf(cmsJudVolume2.getVolTotalPage()) || objects.size() == 0L ||
                StringUtils.isBlank(cmsJudVolume2.getVolTotalPage())) {
            //校验页次
            //卷归档错误
            return "卷内件页次超过改卷总页数";
        }

        //添加件数
        cmsJudVolume2.setVolItemNumber(String.valueOf(cmsJudIt.size()));

        //生成档号
        String fileNumber = null;
        try {
            fileNumber = volAndItemService.getFileNumber(cmsJudVolume2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("error".equals(fileNumber) || StringUtils.isBlank(fileNumber)) {
            return "构成档号的著录项为空";
        }
        int i=0;
        if(StringUtils.isNotBlank(archiveStatus) && "0".equals(archiveStatus)){
           //使用原档号强制归档
            errorArchiveItem(volId, fileNumber);
            cmsJudVolume2.setVolArchiveStatus(2);
            i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume2);
        }else {
            //使用新生档号归档
            errorArchiveItem(volId, fileNumber);
            cmsJudVolume2.setVolCaseNum(fileNumber);
            cmsJudVolume2.setVolArchiveStatus(2);
            i = volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume2);
        }
        if(i==0){
            return "归档失败";
        }else {
            return "success";
        }
    }

    private void errorArchiveItem(String volId, String fileNumber) {
        List<CmsJudItem> cmsJudItems = volAndItemService.selectAllByVolId(Long.valueOf(volId), 2);
        for (CmsJudItem cmsJudItem : cmsJudItems) {
            if(StringUtils.isBlank(cmsJudItem.getItemStr8())|| "2".equals(cmsJudItem.getItemStr8())){
                //使用新生件号
               // String str = String.format("%04d", cmsJudItem.getItemPage());
                // 将 件号=档号+页次 修改为 件号=档号+序号
                String str = String.format("%04d", cmsJudItem.getItemNum());
                String fileItemNumber = fileNumber + "-" + str;
                cmsJudItem.setItemStr1(fileItemNumber);
            }
            cmsJudItem.setItemStr11Date(DateTimeUtil.getNow());
            int i1 = cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
        }
    }

    @ApiOperation(value = "使用原档号强制归档")
    @RequestMapping(value = "/beforeVolError", method = RequestMethod.POST)
    @ResponseBody
    public String beforeVolError(HttpServletRequest request,String volId) {
        CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(Long.valueOf(volId));
        cmsJudVolume.setVolStr6("1");
        int i = cmsJudVolumeMapper.updateByPrimaryKey(cmsJudVolume);
        if(i==0){
            return "确定失败！";
        }else {
            return "success";
        }
    }

    @ApiOperation(value = "使用原件号强制归档")
    @RequestMapping(value = "/beforeItemError", method = RequestMethod.POST)
    @ResponseBody
    public String beforeItemError(HttpServletRequest request,String itemId) {
        CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(Long.valueOf(itemId));
        cmsJudItem.setItemStr8("1");
        int i = cmsJudItemMapper.updateByPrimaryKey(cmsJudItem);
        if(i==0){
            return "确定失败！";
        }else {
            return "success";
        }
    }

    @ApiOperation(value = "使用新生成件号归档")
    @RequestMapping(value = "/nowItemError", method = RequestMethod.POST)
    @ResponseBody
    public String nowItemError(HttpServletRequest request,String itemId) {
        CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(Long.valueOf(itemId));
        if(StringUtils.isBlank(cmsJudItem.getItemStr7())|| cmsJudItem.getItemStr7()=="NULL"){
            return "未生成新件号";
        }else {
            cmsJudItem.setItemStr8("2");
            int i = cmsJudItemMapper.updateByPrimaryKey(cmsJudItem);
            if(i==0){
                return "确定失败！";
            }else {
                return "success";
            }
        }
    }

    @ApiOperation(value = "打印卷内目录(自定义)")
    @RequestMapping(value = "/print/printRowsGen")
    @ResponseBody
    public Object tearOrderModal(HttpServletRequest request, HttpSession session,
                                    @RequestParam(required = false, value = "printRows") String printRows,
                                    @RequestParam(required = false, value = "volIdPrint") String volIdPrint) {
        //第二种方式
        List<String> columnsHeadList = new ArrayList<String>();
        columnsHeadList = JSONObject.parseArray(printRows,String.class);//反射获取String的对象类

        //通过卷id查询所有卷内件
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criter = cmsJudItemExample.createCriteria();
        criter.andItmeVolIdEqualTo(Long.valueOf(volIdPrint));
        cmsJudItemExample.setOrderByClause("\"ITEM_NUM\" ASC");//按顺序号排序
        List<CmsJudItem> cmsJu = cmsJudItemMapper.selectByExample(cmsJudItemExample);

        //存放每列的数据，String[]为列头，List<Object>为每列的值
        Map<String, List<Object>> listHashMap = new HashMap<>();

        //传入打印卷内件标题
        String titleFont="文件目录";
        //查出数据的量
        int size = cmsJu.size();

        String nowMilliseconds = DateTimeUtil.getNowMilliseconds();

        //获取新存放文件路径
        //String newPath = session.getServletContext().getRealPath("/") + "\\localpdf\\itemCatalogPDF"+nowMilliseconds+".pdf";
        String realPath = session.getServletContext().getRealPath("/");
        if (realPath.contains("target")){
            String target = realPath.split("target")[0];
            realPath=target+"src\\main\\webapp";
        }
        String newPath = realPath + "\\localpdf\\itemCatalogPDF"+nowMilliseconds+".pdf";

        //list存放列数据
        try {
            for (String st : columnsHeadList) {
                List<Object> value = new ArrayList<>();//存放列数据
                String[] split = st.split("\\|");
                String fieldsValue = split[1];
                for (CmsJudItem cmsJudItem : cmsJu) {
                    Class clazz = cmsJudItem.getClass();
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldsValue, clazz);
                    Method readMethod = propertyDescriptor.getReadMethod();
                    Object invoke = readMethod.invoke(cmsJudItem);
                    value.add(invoke);
                }
                listHashMap.put(split[0],value);
            }

            //size：写入文件的总数，titleFont:文件的标题，
            // columnsHeadList:列头list集合(包含列数，字段名，中文名)
            //listHashMap:列数据集合(key为列数，value为该列数据)
            byte[] bytes = ProducePdf.producePdf(newPath, size, titleFont, columnsHeadList, listHashMap);
            //上传FastDfs
            FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
            String fastDfSUrl = fastDFSClient.uploadFile(bytes,"pdf");
            String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;

            if(StringUtils.isBlank(fastDfSUrl)){
                return new CmsResult(CmsResultConstant.FAILED, 0);
            }
            return new CmsResult(CmsResultConstant.SUCCESS, imagesUrl);

        } catch (Exception e) {
            LOGGER.error("创建pdf打印文件，存放至临时地址IO读写异常"+e);
            e.printStackTrace();
        }

        return new CmsResult(CmsResultConstant.FAILED, 0);
    }

    @ApiOperation(value = "打印卷内目录(固定模板)")
    @RequestMapping(value = "/print/printVolumeFixed")
    @ResponseBody
    public Object printVolumeFixed(HttpServletRequest request, HttpSession session,
                                 String volId) {
        //卷信息
        CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(Long.valueOf(volId));
        String volClass = cmsJudVolume.getVolClass();
        //卷类型
        List<UpmsArchivesTypes> allTypes = upmsArchivesTypesService.findArchiveTypeByArchiveNum(volClass);
        String volClassName = allTypes.size() == 0 ? null : allTypes.get(0).getSortName();
        //卷保管期限
        List<UpmsDictionary> storageTimeTypeByCode = upmsDictionaryService.findStorageTimeTypeByCode(cmsJudVolume.getVolStorageTime());
        String volStorageTimeName = storageTimeTypeByCode.size() == 0 ? null : storageTimeTypeByCode.get(0).getDescription();
        //卷密级
        String volSecretName=null;
        if(StringUtils.isNotBlank(cmsJudVolume.getVolSecret())){
            List<UpmsDictionary> volSecretCode = upmsDictionaryService.findStorageTimeTypeByCode(cmsJudVolume.getVolSecret());
            volSecretName = volSecretCode.size() == 0 ? null : volSecretCode.get(0).getDescription();
        }

        //卷归档单位
        UpmsOrganization organizationById = upmsOrganizationService.getOrganizationById(Long.valueOf(cmsJudVolume.getVolArchiveUnit()));
        String volArchiveUnitName = organizationById == null ? null : organizationById.getName();

        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("volClassName",volClassName+"卷内目录");
        //题名
        headMap.put("volTitle",cmsJudVolume.getVolTitle());
        //归档年度
        headMap.put("volArchiveYear",cmsJudVolume.getVolArchiveYear());
        //审计组长
        headMap.put("volAuditLeader",cmsJudVolume.getVolAuditLeader());
        //保管期限
        headMap.put("volStorageTime",volStorageTimeName);
        //归档单位
        headMap.put("volArchiveUnit",volArchiveUnitName);
        //审计时间
        headMap.put("volAuditDate",cmsJudVolume.getVolAuditDate());
        //案卷号
        headMap.put("volNo",cmsJudVolume.getVolNo());
        //总卷数
        headMap.put("volTotal","本 项 目 共 "+cmsJudVolume.getVolTotal()+" 卷");
        //当前卷数
        headMap.put("volCurrent","本 卷 为 第 "+cmsJudVolume.getVolCurrent()+" 卷");
        //密级
        headMap.put("volSecret",volSecretName);
        //卷内件
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criter = cmsJudItemExample.createCriteria();
        criter.andItmeVolIdEqualTo(Long.valueOf(volId));
        //按顺序号排序
        cmsJudItemExample.setOrderByClause("\"ITEM_NUM\" ASC");
        List<CmsJudItem> cmsJud = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        for (int i = 0; i < cmsJud.size(); i++) {
            if(i==cmsJud.size()-1){
               /* if(cmsJud.get(i).getItemPage().toString().equals(cmsJudVolume.getVolTotalPage())){
                    String itemPageNoName1 =cmsJud.get(i).getItemPage().toString();
                    cmsJud.get(i).setItemPageNo(itemPageNoName1);
                }else {*/
                    String itemPageNoName2 = cmsJud.get(i).getItemPage() + "-" + cmsJudVolume.getVolTotalPage();
                    cmsJud.get(i).setItemPageNo(itemPageNoName2);
                /*}*/
            }else {
                Long itemPageEnd = cmsJud.get(i + 1).getItemPage()-1;
                String itemPageNoName3 = cmsJud.get(i).getItemPage() + "-" + itemPageEnd;
                cmsJud.get(i).setItemPageNo(itemPageNoName3);
            }
            //卷内件密级(将件的密级有code值变为Name)
            if(StringUtils.isNotBlank(cmsJud.get(i).getItemSecret())){
                List<UpmsDictionary> itemSercrets = upmsDictionaryService.findStorageTimeTypeByCode(cmsJud.get(i).getItemSecret());
                String itemSercret = itemSercrets.size() == 0 ? null : itemSercrets.get(0).getDescription();
                cmsJud.get(i).setItemSecret(itemSercret);
            }else {
                cmsJud.get(i).setItemSecret(null);
            }

        }
        try{
            byte[] bytes = ProducePdf.producePdfFixed(headMap, cmsJud);
            //上传FastDfs
            FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
            String fastDfSUrl = fastDFSClient.uploadFile(bytes,"pdf");
            String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;

            if(StringUtils.isBlank(fastDfSUrl)){
                return new CmsResult(CmsResultConstant.FAILED, 0);
            }
            return new CmsResult(CmsResultConstant.SUCCESS, imagesUrl);
        } catch (Exception e) {
            LOGGER.error("创建pdf打印文件，存放至临时地址IO读写异常"+e);
            e.printStackTrace();
        }

        return new CmsResult(CmsResultConstant.FAILED, 0);
    }


    @ApiOperation(value = "删除临时保存的打印卷内目录")
    @RequestMapping(value = "/print/delOpenPdf")
    @ResponseBody
    public Object delOpenPdf(HttpServletRequest request,HttpSession session,
                             @RequestParam(required = false, value = "openMilliseconds") String openMilliseconds) {
        //获取新存放文件路径
        //FastDfs删除卷内件
        FastDfsClient fastDFSClient = null;
        //FastDfs返回为0,删除成功
        int i=1;
        try {
            fastDFSClient = new FastDfsClient("classpath:client.conf");
            String shortUrl = openMilliseconds.replaceAll(IMAGE_SERVER_URL, "").trim();
            i = fastDFSClient.deleteFile(shortUrl);
        } catch (Exception e) {
            LOGGER.error("FastDfs删除文件错误,内容:"+e);
            e.printStackTrace();
        }

       if(i==0){
             return new CmsResult(CmsResultConstant.SUCCESS, 0);
        }else{
           return new CmsResult(CmsResultConstant.FAILED, 1);
       }
    }

    @ApiOperation(value = "查询所有卷")
    //@RequiresPermissions("cms:archive:read")
    @RequestMapping(value = "/archive/allSelect")
    @ResponseBody
    public Object allSelect() {
        CmsJudVolumeExample cmsJudVolumeExample = new CmsJudVolumeExample();
        CmsJudVolumeExample.Criteria criteria = cmsJudVolumeExample.createCriteria();
        criteria.andVolArchiveStatusEqualTo(1);//待归档
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(1);
        integers.add(4);
        criteria.andVolArchiveStatusIn(integers);
        criteria.andVolStatusEqualTo(0);//案卷状态正常
        List<CmsJudVolume> allVolume = cmsJudVolumeMapper.selectByExample(cmsJudVolumeExample);
        if (allVolume.size() == 0) {
            return new CmsResult(CmsResultConstant.FAILED, 0);
        }
        JSONArray jsonArray = JSONArray.fromObject(allVolume);
        String s = jsonArray.toString();
        return new CmsResult(CmsResultConstant.SUCCESS, s);
    }

    @ApiOperation(value = "卷内件列表,排序页面")
    @RequestMapping(value = "/archive/orAdjustOrder")
    @ResponseBody
    public Object orAdjustOrder(@RequestParam(required = false, value = "volId") Long volId) {
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria1 = cmsJudItemExample.createCriteria();
        //该件已组卷状态，1：为已组卷，0：未组卷
        criteria1.andItemVolumeIdEqualTo((long) 1);
        criteria1.andItmeVolIdEqualTo(Long.valueOf(volId));//件中卷的外键
        cmsJudItemExample.setOrderByClause("\"ITEM_NUM\" ASC");
        List<CmsJudItem> rows = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        int total = cmsJudItemMapper.countByExample(cmsJudItemExample);
        Map<String, Object> result = new HashMap<>(2);
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "卷内排序")
    @RequestMapping(value = "/archive/sort")
    @ResponseBody
    public Object sort(@RequestParam(required = false, value = "newData") String newData) {
        List<CmsJudItem> list = new ArrayList<CmsJudItem>();
        list = JSONObject.parseArray(newData, CmsJudItem.class);
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            CmsJudItem cmsJudItem = list.get(i);
            cmsJudItem.setItemNum((long) i + 1);
            count = cmsJudItemMapper.updateByPrimaryKey(list.get(i));
        }
        if(count!=1){
            return new CmsResult(CmsResultConstant.FAILED, 0);
        }
        return new CmsResult(CmsResultConstant.SUCCESS,1);
    }

    @ApiOperation(value = "分卷的文件列表所有数据处理")
    @RequestMapping(value = "/archive/deleteVolume")
    @ResponseBody
    public Object deleteVolume(
            @RequestParam(required = false, value = "beforeData1") String beforeData1,
            @RequestParam(required = false, value = "afterData2") String afterData2,
            @RequestParam(required = false, value = "volIdBeforeSeg") long volIdBeforeSeg,
            @RequestParam(required = false, value = "volIdAfterSeg") long volIdAfterSeg) {
        //先根据新卷的ID查出新卷的案卷号volCaseNum，全宗号volFian,案卷级档号volArchiveNum
        CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(volIdAfterSeg);
        //右边
        List<CmsJudItem> itemlist = JSONObject.parseArray(afterData2, CmsJudItem.class);
        ArrayList<Object> status = new ArrayList<>();
        for (int i = 0; i < itemlist.size(); i++) {
            long itemNum=(long) i + 1;
            Long itemId =  itemlist.get(i).getItemId();
            //根据每个件的ID查出每个件，遍历每个件，拿到件的信息
            CmsJudItem newItem = cmsJudItemMapper.selectByPrimaryKey(itemId);
            //件关联的卷外键
            newItem.setItmeVolId(volIdAfterSeg);
            //更改每个件的顺序号
            newItem.setItemNum(itemNum);
            //件号
            if(StringUtils.isNotBlank(cmsJudVolume.getVolCaseNum())){
                String str = String.format("%04d", newItem.getItemPage());
                newItem.setItemStr1(cmsJudVolume.getVolCaseNum()+"-"+str);
            }
            //修改时间
            Date now = DateTimeUtil.getNow();
            newItem.setItemEditDate(now );
            int count  = cmsJudItemMapper.updateByPrimaryKeySelective(newItem);
            if (count != 1) {
                status.add(count);
            }
        }
        //查询出原案卷的所有件，重新编号.左边
        List<CmsJudItem> orItemlist = JSONObject.parseArray(beforeData1, CmsJudItem.class);
        CmsJudVolume orCmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(volIdBeforeSeg);
        ArrayList<Object> status2 = new ArrayList<>();
        for (int i = 0; i < orItemlist.size(); i++) {
            Long orItemId = orItemlist.get(i).getItemId();
            //根据每个件的ID查出每个件，遍历每个件，拿到件的信息
            CmsJudItem orNewItem = cmsJudItemMapper.selectByPrimaryKey(orItemId);
            CmsJudItem orCmsJudItem = orItemlist.get(i);
            orCmsJudItem.setItemNum((long) i + 1);
            //件关联的卷外键
            orCmsJudItem.setItmeVolId(volIdBeforeSeg);
            //修改时间
            Date now = DateTimeUtil.getNow();
            orCmsJudItem.setItemEditDate(now );
            //件号
            if(StringUtils.isNotBlank(orCmsJudVolume.getVolCaseNum())){
                String str = String.format("%04d", orNewItem.getItemPage());
                orCmsJudItem.setItemStr1(orCmsJudVolume.getVolCaseNum()+"-"+str);
            }
            int i1 = cmsJudItemMapper.updateByPrimaryKey(orCmsJudItem);
            if (i1 != 1) {
                status2.add(i1);
            }
        }
        if (status.size() != 0||status2.size()!=0) {
            return new CmsResult(CmsResultConstant.FAILED, 0);
        }
        return new CmsResult(CmsResultConstant.SUCCESS, 1);
    }

    @ApiOperation(value = "未组卷件查询")
    @RequestMapping(value = "/archive/selectItemNot")
    @ResponseBody
    public String selectItemNot() {
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria1 = cmsJudItemExample.createCriteria();
        //该件已组卷状态，1：为已组卷，0：未组卷
        criteria1.andItemVolumeIdEqualTo((long) 0);
        cmsJudItemExample.setOrderByClause("\"ITEM_EDIT_DATE\" DESC");
        List<CmsJudItem> rows = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        JSONArray jsonArray = JSONArray.fromObject(rows);
        String string = jsonArray.toString();
        return string;
    }

    @ApiOperation(value = "合卷提交")
    @RequestMapping(value = "/sortOut/coVolume")
    @ResponseBody
    public String coVolume(@RequestParam(required = false, value = "volId") String volId,
                           @RequestParam(required = false, value = "idsItem") String idsItem) {
        CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(Long.valueOf(volId));
        String[] split = idsItem.split("-");
        ArrayList<Object> objects = new ArrayList<>();
        for (String itemId : split) {
            CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(Long.valueOf(itemId));
            cmsJudItem.setItmeVolId(cmsJudVolume.getVolId());
            cmsJudItem.setItemVolumeId(1L);//修改为已组卷
            String str = String.format("%04d", cmsJudItem.getItemPage());
            cmsJudItem.setItemStr1(cmsJudVolume.getVolCaseNum()+"-"+str);
            cmsJudItem.setItemEditDate(DateTimeUtil.getNow());
            int i = cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
            if(i==0){
                objects.add(cmsJudItem.getItemTitle());
            }
        }
        if(objects.size()!=0){
            String join = StringUtils.join(objects.toArray(), ",");
            return join+"合入失败,请稍后重试!";
        }
        return "success";
    }

    @ApiOperation(value = "根据卷Id查询卷内件")
    @RequestMapping(value = "/archive/selectVolItemAll")
    @ResponseBody
    public String selectVolItemAll(@RequestParam(required = false, value = "volId") String volId) {
        List<CmsJudItem> cmsJudItems = volAndItemService.selectAllByVolId(Long.valueOf(volId), 2);
        JSONArray jsonArray = JSONArray.fromObject(cmsJudItems);
        String string = jsonArray.toString();
        return string;
    }

    @ApiOperation(value = "拆卷提交")
    @RequestMapping(value = "/archive/moveOutItem")
    @ResponseBody
    public String moveOutItem(@RequestParam(required = false, value = "unItems") String unItems,
                           @RequestParam(required = false, value = "unVolId") String unVolId) {
        String[] splits = unItems.split("-");
        ArrayList<Object> objUn = new ArrayList<>();
        for (String itemId : splits) {
            CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(Long.valueOf(itemId));
            cmsJudItem.setItmeVolId(null);
            cmsJudItem.setItemVolumeId(0L);//修改未组卷
            cmsJudItem.setItemStr1(null);
            cmsJudItem.setItemEditDate(DateTimeUtil.getNow());
            int i = cmsJudItemMapper.updateByPrimaryKey(cmsJudItem);
            if(i==0){
                objUn.add(cmsJudItem.getItemTitle());
            }
        }
        if(objUn.size()!=0){
            String join = StringUtils.join(objUn.toArray(), ",");
            return join+"移出失败,请稍后重试!";
        }
        return "success";
    }


}
